package com.zego.wawaji.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.KeyEvent;
import android.view.View;

import com.zego.wawaji.R;
import com.zego.wawaji.base.log.PToast;
import com.zego.wawaji.base.module.ModuleMgr;
import com.zego.wawaji.base.observer.MsgMgr;
import com.zego.wawaji.base.observer.MsgType;
import com.zego.wawaji.base.observer.PObserver;
import com.zego.wawaji.third.zego.ZegoMgr;
import com.zego.wawaji.ui.Fragment.BaseFragment;
import com.zego.wawaji.ui.Fragment.play.PlayFragment;
import com.zego.wawaji.ui.Fragment.store.StoreFragment;
import com.zego.wawaji.ui.Fragment.user.UserFragment;
import com.zego.wawaji.ui.Fragment.wawa.WawaFragment;
import com.zego.wawaji.ui.Fragment.web.RankFragment;
import com.zego.wawaji.ui.UIShow;
import com.zego.wawaji.ui.base.BaseAppCompatActivity;
import com.zego.wawaji.wawaji_client.App;

public class MainActivity extends BaseAppCompatActivity implements View.OnClickListener, PObserver {
    private FragmentManager fragmentManager;
    private PlayFragment playFragment;             // 首页
    private UserFragment userFragment;
    private WawaFragment wawaFragment;
    private StoreFragment storeFragment;
    private RankFragment rankFragment;

    private BaseFragment current;  // 当前的fragment
    private View[] views;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isCanBack(false);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initViews();
        initFragment();
    }

    private void reqData() {
        ModuleMgr.getWawaMgr().reqPayListNew(null);

        if (App.isNewUser) {  // 新用户
            App.isNewUser = false;
            ModuleMgr.getWawaMgr().reqYQCode();
        } else {
            ModuleMgr.getWawaMgr().reqNewVersion(false, null);
        }
    }

    private void initViews() {
        MsgMgr.getInstance().attach(this);
        View play_layout = findViewById(R.id.play_layout);
        View user_layout = findViewById(R.id.user_layout);
        View wawa_layout = findViewById(R.id.wawa_layout);
        View store_layout = findViewById(R.id.store_layout);
        View web_layout = findViewById(R.id.web_layout);

        views = new View[]{play_layout, wawa_layout, web_layout, store_layout, user_layout};
        play_layout.setOnClickListener(this);
        user_layout.setOnClickListener(this);
        wawa_layout.setOnClickListener(this);
        store_layout.setOnClickListener(this);
        web_layout.setOnClickListener(this);
        reqData();
    }

    private void initFragment() {
        fragmentManager = getSupportFragmentManager();
        playFragment = new PlayFragment();
        userFragment = new UserFragment();
        wawaFragment = new WawaFragment();
        storeFragment = new StoreFragment();
        rankFragment = new RankFragment();

        switchContent(playFragment);
    }

    /**
     * 切换当前显示的fragment
     */
    private void switchContent(BaseFragment fragment) {
        tabSwitchStatus(fragment);

        if (current != fragment) {
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            if (current != null) {
                transaction.hide(current);
            }
            if (!fragment.isAdded()) { //先判断是否被add过
                transaction.add(R.id.content, fragment).commitAllowingStateLoss();
            } else {
                transaction.show(fragment).commitAllowingStateLoss(); // 隐藏当前的fragment，显示下一个
            }
            fragmentManager.executePendingTransactions();
            current = fragment;
        }
    }

    /**
     * fragment切换的时候的状态判断以及请求
     *
     * @param fragment 切换的fragment
     */
    private void tabSwitchStatus(BaseFragment fragment) {
        if (fragment == playFragment) {
            tabSwitchHandler.sendEmptyMessage(R.id.play_layout);
        } else if (fragment == userFragment) {
            tabSwitchHandler.sendEmptyMessage(R.id.user_layout);
        } else if (fragment == wawaFragment) {
            tabSwitchHandler.sendEmptyMessage(R.id.wawa_layout);
        } else if (fragment == storeFragment) {
            tabSwitchHandler.sendEmptyMessage(R.id.store_layout);
        } else if (fragment == rankFragment) {
            tabSwitchHandler.sendEmptyMessage(R.id.web_layout);
        }
    }

    private Handler tabSwitchHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            for (View view : views) {
                // 底部tab选中效果
                view.setSelected(msg.what == view.getId());
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_layout:
                switchContent(playFragment);
                break;
            case R.id.user_layout:
                switchContent(userFragment);
                break;
            case R.id.wawa_layout:
                switchContent(wawaFragment);
                break;
            case R.id.store_layout:
                switchContent(storeFragment);
                break;
            case R.id.web_layout:
                switchContent(rankFragment);
                break;
        }
    }

    @Override
    public void onMessage(String key, Object value) {
        switch (key) {
            case MsgType.MT_App_Login:
                if (!(boolean) value) {
                    UIShow.showNavUserAct(this);
                    finish();
                }
                break;
        }
    }

    @Override
    public void finish() {
        super.finish();
        ZegoMgr.getInstance().releaseSDK();
        MsgMgr.getInstance().detach(this);
        if (wawaFragment != null) {
            wawaFragment.release();
        }
        if (storeFragment != null) {
            storeFragment.release();
        }
    }

    private long firstExitTime = 0;// 用于判断双击退出时间间隔

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            long doubleExitTime = System.currentTimeMillis();
            if (doubleExitTime - firstExitTime < 2000) {
                ModuleMgr.getLoginMgr().updateExitDouble(true);
                finish();//假退出，只关闭当前页面
            } else {
                firstExitTime = doubleExitTime;
                PToast.showShort("确定要离开吗？");
            }
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }
}
